<template>
  <div class="management-layout">
    <div class="layout-container">
      <!-- 左侧菜单栏 -->
      <aside :class="['sidebar', { 'collapsed': sidebarCollapsed }]">
        <div class="toggle-btn" @click="toggleSidebar">
          <span>{{ sidebarCollapsed ? '›' : '‹' }}</span>
        </div>

        <nav class="menu-nav" v-show="!sidebarCollapsed">
          <!-- 管理员功能（仅管理员可见） -->
          <div v-if="isAdministrator" class="menu-section">
            <ul>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'admin-dashboard' }"
                  @click.prevent="openTab('admin-dashboard', $t('message.adminOverview'))"
                >
                  <span class="menu-icon">📊</span>
                  <span class="menu-text">{{ $t('message.adminOverview') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'teacher-verification' }"
                  @click.prevent="openTab('teacher-verification', $t('message.teacherVerification'))"
                >
                  <span class="menu-icon">✅</span>
                  <span class="menu-text">{{ $t('message.teacherVerification') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'admin-settings' }"
                  @click.prevent="openTab('admin-settings', $t('message.adminSettings'))"
                >
                  <span class="menu-icon">⚙️</span>
                  <span class="menu-text">{{ $t('message.adminSettings') }}</span>
                </a>
              </li>
            </ul>
          </div>

          <!-- 教师功能（仅教师可见） -->
          <div v-else-if="isTeacher" class="menu-section">
            <ul>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'teacher-schedule' }"
                  @click.prevent="openTab('teacher-schedule', $t('message.schedule'))"
                >
                  <span class="menu-icon">📅</span>
                  <span class="menu-text">{{ $t('message.schedule') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'teacher-classes' }"
                  @click.prevent="openTab('teacher-classes', $t('message.myClasses'))"
                >
                  <span class="menu-icon">📚</span>
                  <span class="menu-text">{{ $t('message.myClasses') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'teacher-students' }"
                  @click.prevent="openTab('teacher-students', $t('message.students'))"
                >
                  <span class="menu-icon">👥</span>
                  <span class="menu-text">{{ $t('message.students') }}</span>
                </a>
              </li>
            </ul>
          </div>

          <!-- 家长功能（仅家长可见） -->
          <div v-else-if="isParent" class="menu-section">
            <ul>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'parent-children' }"
                  @click.prevent="openTab('parent-children', $t('message.myChildren'))"
                >
                  <span class="menu-icon">👨‍👩‍👧</span>
                  <span class="menu-text">{{ $t('message.myChildren') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'parent-schedule' }"
                  @click.prevent="openTab('parent-schedule', $t('message.mySchedule'))"
                >
                  <span class="menu-icon">📅</span>
                  <span class="menu-text">{{ $t('message.mySchedule') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'parent-bookings' }"
                  @click.prevent="openTab('parent-bookings', $t('message.bookings'))"
                >
                  <span class="menu-icon">📝</span>
                  <span class="menu-text">{{ $t('message.bookings') }}</span>
                </a>
              </li>
            </ul>
          </div>

          <!-- 助教功能（仅助教可见） -->
          <div v-else-if="isAssistant" class="menu-section">
            <ul>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'assistant-assigned' }"
                  @click.prevent="openTab('assistant-assigned', $t('message.assignedTasks'))"
                >
                  <span class="menu-icon">📋</span>
                  <span class="menu-text">{{ $t('message.assignedTasks') }}</span>
                </a>
              </li>
              <li>
                <a
                  href="#"
                  class="menu-item"
                  :class="{ active: activeTab === 'assistant-schedule' }"
                  @click.prevent="openTab('assistant-schedule', $t('message.mySchedule'))"
                >
                  <span class="menu-icon">📅</span>
                  <span class="menu-text">{{ $t('message.mySchedule') }}</span>
                </a>
              </li>
            </ul>
          </div>
        </nav>
      </aside>

      <!-- 主内容区域 -->
      <main class="main-content">
        <!-- 标签页栏 -->
        <div class="tabs-bar">
          <div
            v-for="(tab, index) in openedTabs"
            :key="tab.name"
            class="tab-item"
            :class="{ active: activeTab === tab.name }"
            @click="switchTab(tab.name)"
          >
            <span>{{ tab.title }}</span>
            <span class="tab-close" @click.stop="closeTab(index)">×</span>
          </div>
        </div>

        <!-- 内容区域 -->
        <div class="content-area">
          <!-- 每个标签页的内容 -->
          <div v-if="activeTab === 'admin-dashboard'" class="tab-content">
            <AdminDashboard />
          </div>
          <div v-if="activeTab === 'teacher-verification'" class="tab-content">
            <TeacherVerification />
          </div>
          <div v-if="activeTab === 'admin-settings'" class="tab-content">
            <AdminSettings />
          </div>
          <div v-if="activeTab === 'teacher-schedule'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.teacherSchedule') }}</h2>
              <p>{{ $t('message.teacherScheduleContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'teacher-classes'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.myClasses') }}</h2>
              <p>{{ $t('message.classesContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'teacher-students'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.students') }}</h2>
              <p>{{ $t('message.studentsContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'parent-children'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.myChildren') }}</h2>
              <p>{{ $t('message.childrenContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'parent-schedule'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.mySchedule') }}</h2>
              <p>{{ $t('message.parentScheduleContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'parent-bookings'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.bookings') }}</h2>
              <p>{{ $t('message.bookingsContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'assistant-assigned'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.assignedTasks') }}</h2>
              <p>{{ $t('message.assignedContent') }}</p>
            </div>
          </div>
          <div v-if="activeTab === 'assistant-schedule'" class="tab-content">
            <div class="tab-placeholder">
              <h2>{{ $t('message.mySchedule') }}</h2>
              <p>{{ $t('message.assistantScheduleContent') }}</p>
            </div>
          </div>

          <!-- 默认欢迎信息 -->
          <div v-if="openedTabs.length === 0" class="tab-placeholder">
            <h2>{{ $t('message.welcome') }}</h2>
            <p>{{ $t('message.selectFunctionFromMenu') }}</p>
          </div>
        </div>
      </main>
    </div>

    <!-- 底部栏 -->
    <footer class="bottom-footer">
      <p>&copy; 2025 {{ $t('message.youkeTutoringPlatform') }}. {{ $t('message.allRightsReserved') }}</p>
    </footer>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useAuthStore } from '@/stores/auth';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import AdminDashboard from '@/views/admin/AdminDashboard.vue';
import TeacherVerification from '@/views/admin/TeacherVerification.vue';
import AdminSettings from '@/views/admin/AdminSettings.vue';

export default {
  name: 'ManagementLayout',
  components: {
    AdminDashboard,
    TeacherVerification,
    AdminSettings
  },
  setup() {
    const { t } = useI18n();
    const router = useRouter();
    const authStore = useAuthStore();

    // 菜单展开/收起状态
    const sidebarCollapsed = ref(false);

    // 标签页管理
    const openedTabs = ref([]);
    const activeTab = ref('');

    // 状态计算
    const user = computed(() => authStore.user);
    const isLoggedIn = computed(() => authStore.isLoggedIn);
    const isAdministrator = computed(() => user.value?.roleId === 'ADMIN');
    const isTeacher = computed(() => user.value?.roleId === 'TEACHER');
    const isParent = computed(() => user.value?.roleId === 'PARENT');
    const isAssistant = computed(() => user.value?.roleId === 'ASSISTANT');

    // 切换侧边栏收起/展开状态
    const toggleSidebar = () => {
      sidebarCollapsed.value = !sidebarCollapsed.value;
    };

    // 打开新标签页
    const openTab = (name, title) => {
      // 检查是否已存在标签
      const existingTab = openedTabs.value.find(tab => tab.name === name);
      if (!existingTab) {
        openedTabs.value.push({ name, title });
      }
      activeTab.value = name;
    };

    // 切换当前标签页
    const switchTab = (name) => {
      activeTab.value = name;
    };

    // 关闭标签页
    const closeTab = (index) => {
      const tabToRemove = openedTabs.value[index];
      openedTabs.value.splice(index, 1);

      // 如果关闭的是当前激活的标签页，切换到其他标签或回到首页
      if (tabToRemove.name === activeTab.value) {
        if (openedTabs.value.length > 0) {
          // 切换到下一个标签，如果没有则切换到最后一个
          const newIndex = index > 0 ? index - 1 : 0;
          activeTab.value = openedTabs.value[newIndex].name;
        } else {
          activeTab.value = '';
        }
      }
    };

    // 登出函数
    const logout = () => {
      authStore.logout();
      router.push('/login');
    };

    // 默认打开用户对应的角色首页
    if (isAdministrator.value) {
      openTab('admin-dashboard', t('message.home'));
    } else if (isTeacher.value) {
      openTab('teacher-schedule', t('message.schedule'));
    } else if (isParent.value) {
      openTab('parent-children', t('message.myChildren'));
    } else if (isAssistant.value) {
      openTab('assistant-assigned', t('message.assignedTasks'));
    }

    return {
      sidebarCollapsed,
      openedTabs,
      activeTab,
      user,
      isLoggedIn,
      isAdministrator,
      isTeacher,
      isParent,
      isAssistant,
      toggleSidebar,
      openTab,
      switchTab,
      closeTab,
      logout,
      t
    };
  }
};
</script>

<style scoped>
.management-layout {
  height: 100vh; /* 使用视口全高度 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.top-header {
  background-color: #3498db;
  color: white;
  padding: 1rem;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logo-area h2 {
  margin: 0;
  color: #1890ff;
  font-size: 18px;
  font-weight: 600;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-center {
  flex: 1;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.welcome-text {
  margin: 0;
  color: #001529;
  font-size: 18px;
  font-weight: 600;
}

.header-links a,
.welcome-msg {
  color: white;
  margin-left: 1rem;
  text-decoration: none;
}

.welcome-msg {
  font-weight: bold;
}

.sidebar {
  width: 256px;
  background-color: white;
  box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 99;
  display: flex;
  flex-direction: column;
  transition: all 0.3s ease;
}

.sidebar.collapsed {
  width: 60px;
}

.toggle-btn {
  position: absolute;
  top: 0;
  right: -20px;
  background: #1890ff;
  color: white;
  width: 20px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
  z-index: 100;
  margin-top: 0;
}

.menu-nav {
  padding: 0 0.5em; /* 上下为0，左右为0.5em */
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  width: 100%; /* 确保占满侧边栏宽度 */
}

.menu-section ul {
  list-style: none;
  padding: 0;
  margin: 0;
  text-align: left; /* 文字左对齐 */
  width: calc(100% - 1em); /* 宽度为100%减去左右各0.5em的padding，共1em */
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 24px;
  color: #595959;
  text-decoration: none;
  transition: all 0.3s ease;
  border-left: 3px solid transparent;
}

.menu-item:hover {
  background-color: #f6ffed;
  color: #52c41a;
  border-left: 3px solid #1890ff;
}

.menu-item.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border-left: 3px solid #1890ff;
}

.menu-icon {
  margin-right: 12px;
  font-size: 16px;
  width: 24px;
  text-align: center;
}

.menu-text {
  flex: 1;
  font-size: 14px;
}

.sidebar.collapsed .menu-text {
  display: none;
}

.sidebar.collapsed .menu-icon {
  margin-right: 0;
  font-size: 18px;
}

.layout-container {
  flex: 1;
  margin-left: 256px; /* 为sidebar预留空间 */
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  height: calc(100vh - 48px); /* 视口高度减去底部footer高度 */
  padding-bottom: 48px; /* 为footer预留空间 */
}

.sidebar.collapsed + .layout-container {
  margin-left: 60px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
  min-width: 0; /* Flex子项目的最小尺寸设置为0 */
  overflow: hidden; /* 防止出现不必要的滚动 */
  margin: 0;
  padding: 0;
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.tabs-bar {
  display: flex;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  overflow-x: auto;
  white-space: nowrap;
  padding: 0 8px;
  flex-shrink: 0;
}

.tab-item {
  padding: 8px 20px;
  background-color: #fafafa;
  border: 1px solid #e8e8e8;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  margin-right: 4px;
  cursor: pointer;
  position: relative;
  display: inline-flex;
  align-items: center;
}

.tab-item.active {
  background-color: white;
  border-bottom: 1px solid white;
  color: #1890ff;
  font-weight: 500;
  margin-bottom: -1px;
}

.tab-close {
  margin-left: 8px;
  width: 18px;
  height: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  font-size: 12px;
}

.tab-close:hover {
  background-color: #f5f5f5;
  color: #aaa;
}

.content-area {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  background-color: #fff;
  border: 1px solid #e8e8e8;
  border-top: none;
}

.tab-content {
  height: 100%;
}

.tab-placeholder {
  padding: 24px;
  text-align: center;
}

.tab-placeholder h2 {
  margin-bottom: 16px;
  color: #001529;
}

.bottom-footer {
  height: 48px;
  background-color: #ecf0f1;
  padding: 1rem;
  text-align: center;
  color: #7f8c8d;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}

.sidebar.collapsed + .layout-container ~ .bottom-footer {
  left: 60px;
}

@media (max-width: 768px) {
  .sidebar {
    width: 200px; /* 在小屏幕上保持一定宽度 */
  }

  .sidebar.collapsed {
    width: 0;
    overflow: hidden;
  }

  .layout-container {
    margin-left: 0;
  }

  .sidebar.collapsed + .layout-container {
    margin-left: 0;
  }

  .bottom-footer,
  .sidebar.collapsed + .layout-container ~ .bottom-footer {
    left: 0;
  }
}
</style>